package com.hxzy.config.security;

import com.hxzy.config.security.handler.AuthenticationEntryPointImpl;
import com.hxzy.config.security.handler.JwtTokenFilter;
import com.hxzy.config.security.handler.JwtTokenLogoutHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.web.filter.CorsFilter;

/**
 * @Author wy
 * @Description springsecurity核心配置文件
 * EnableGlobalMethodSecurity  方法增强验证操作
 * @Date 2023/9/27 9:04
 * @Version 1.0
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    /**
     * 用户登录认证和授权的操作
     */
    @Autowired
    private UserDetailsService  springSecurityUserDetailServiceImpl;

    /**
     * spring security异常（未认证，权限不足等情况）
     */
    @Autowired
    private AuthenticationEntryPointImpl  authenticationEntryPointImpl;

    /**
     * 令牌有效性的拦截器Filter
     */
    @Autowired
    private JwtTokenFilter   jwtTokenFilter;

    /**
     * 退出当前用户操作
     */
    @Autowired
    private JwtTokenLogoutHandler  jwtTokenLogoutHandler;

    /**
     * 跨域配置Filter
     */
    @Autowired
    private CorsFilter corsFilter;


    /**
     * 后台要放行的地址
     */
    @Value(value = "${token.admin.exclude}")
    private String[] excludeUrl;

    /**
     * 1、重新实例化bean
     */
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 2、配置密码验证策略
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        /*
         encoders.put(encodingId, new BCryptPasswordEncoder());
        encoders.put("ldap", new LdapShaPasswordEncoder());
        encoders.put("MD4", new Md4PasswordEncoder());
        encoders.put("MD5", new MessageDigestPasswordEncoder("MD5"));
        encoders.put("noop", NoOpPasswordEncoder.getInstance());
        encoders.put("pbkdf2", new Pbkdf2PasswordEncoder());
        encoders.put("scrypt", new SCryptPasswordEncoder());
        encoders.put("SHA-1", new MessageDigestPasswordEncoder("SHA-1"));
        encoders.put("SHA-256", new MessageDigestPasswordEncoder("SHA-256"));
        encoders.put("sha256", new StandardPasswordEncoder());
        encoders.put("argon2", new Argon2PasswordEncoder());
         */
        return new BCryptPasswordEncoder();
    }

    /**
     * 3、你是如何去连接数据库(UserDetailService接口)
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(this.springSecurityUserDetailServiceImpl).passwordEncoder(passwordEncoder());
    }

    /**
     * 配置哪些请求要拦截，哪些请要放行，如何放行
     * anyRequest          |   匹配所有请求路径
     * access              |   SpringEl表达式结果为true时可以访问
     * anonymous           |   匿名可以访问
     * denyAll             |   用户不能访问
     * fullyAuthenticated  |   用户完全认证可以访问（非remember-me下自动登录）
     * hasAnyAuthority     |   如果有参数，参数表示权限，则其中任何一个权限可以访问
     * hasAnyRole          |   如果有参数，参数表示角色，则其中任何一个角色可以访问
     * hasAuthority        |   如果有参数，参数表示权限，则其权限可以访问
     * hasIpAddress        |   如果有参数，参数表示IP地址，如果用户IP和参数匹配，则可以访问
     * hasRole             |   如果有参数，参数表示角色，则其角色可以访问
     * permitAll           |   用户可以任意访问
     * rememberMe          |   允许通过remember-me登录的用户访问
     * authenticated       |   用户登录后可访问
     */
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {

        httpSecurity
                // CSRF禁用，因为不使用session
                .csrf().disable()
                // 认证失败处理类
                .exceptionHandling().authenticationEntryPoint(this.authenticationEntryPointImpl)
                .and()
                // 基于token，所以不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                // 过滤请求
                .authorizeRequests()

                // 对于登录login 注册register   允许匿名访问
                .antMatchers( this.excludeUrl).anonymous()
                .antMatchers(
                        HttpMethod.GET,
                        "/",
                        "/*.html",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js",
                        "/profile/**"
                ).permitAll()
                .antMatchers("/swagger-ui.html").anonymous()
                .antMatchers("/doc.html").anonymous()
                .antMatchers("/swagger-resources/**").anonymous()
                .antMatchers("/webjars/**").anonymous()
                .antMatchers("/*/api-docs").anonymous()
                .antMatchers("/druid/**").anonymous()
                // 除上面外的所有请求全部需要鉴权认证
                .antMatchers("/api/**").authenticated()
                .and()
                .headers().frameOptions().disable();

        //自定义拦截器以及处理器放在spring security拦截器里面

        //用户点击登出操作
        httpSecurity.logout().logoutUrl("/api/logout").logoutSuccessHandler(this.jwtTokenLogoutHandler);

        // 添加JWT filter
        httpSecurity.addFilterBefore(this.jwtTokenFilter, UsernamePasswordAuthenticationFilter.class);
        // 添加CORS filter 放到自定义验证之前
        httpSecurity.addFilterBefore(corsFilter, JwtTokenFilter.class);
        //添加cors 放到退出之前
        httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class);
    }


}
